# IPython log file


import cPickle
import math
import histogram
from histogram import dump as hdump
from histogram import load as hload
import tables
import numpy
import matplotlib
from matplotlib import pyplot
import physics
import physics.vector as vector
import os
import glob
from collections import defaultdict
with open("pedmode-respond.dat") as fp:
    bytestr = fp.read()
    
len(bytestr)
len(bytestr) % 4
nwords = len(bytestr) / 4
len(nwords)
nwords
from struct import *
words = unpact("%dI" % nwords, bytestr)
words = unpack("%dI" % nwords, bytestr)
len(words)
from collections import Counter
ctr = Counter()
for w in words:
    ctr[w] += 1
    
ctr[0x65766e74]
for i in xrange(len(words)):
    if words[i] != 0x65766e74:
        continue
    if len(words) <= i+5:
        continue
    if words[i+5] == 0x1:
        ctr['pedmode'] += 1
        
ctr['pedmode']
for i in xrange(len(words)):
    if words[i] != 0x65766e74:
        continue
    if len(words) <= i+5:
        continue
    if words[i+5] == 0x1:
        ctr['pedmode'] += 1
    print hex(words[i+5])
    
packets = []
wpop = words[:]
while len(wpop) > 0:
    w = wpop.pop(0)
    if w == 0xBE11E2:
        packets.append([])
    packets[-1].append(w)
    
wpop = list(wpop)
while len(wpop) > 0:
    w = wpop.pop(0)
    if w == 0xBE11E2:
        packets.append([])
    packets[-1].append(w)
    
len(packets)
def dump_packet(p):
    print '\n'.join(map(hex, p))
    print
    
dump_packet(packets[0])
dump_packet(packets[1])
dump_packet(packets[2])
wfhdr = 0x77617665 
def asic_info(word):
    d = {}
    d['win'] = word & 0x1FF
    d['ch'] = (word & 0xe00) >> 9
    d['row'] = (word & 0x3000) >> 12
    d['col'] = (word & 0xc000) >> 14
    return d
for p in packets:
    if p[2] != wfhdr:
        continue
    d = asic_info(p[6])
    print d['row'], d['col'], d['ch'], d['win']
    
evhdr = 0x65766e74
okay = 0x6F6B6179 
last_cmdid = -1
last_cmdid = 0
for p in packets:
    if p[2] == okay:
        if p[4] > 0xFF:
            last_cmdid = p[4]
    elif p[2] == wfhdr:
        d = asic_info(p[6])
        print d['row'], d['col'], d['ch'], d['win'], hex(last_cmdid)
        
for p in packets:
    if p[2] == okay:
        if p[4] > 0xFF:
            last_cmdid = p[4]
    elif p[2] == wfhdr:
        d = asic_info(p[6])
        print d['row'], d['col'], d['ch'], hex(d['win']), hex(last_cmdid)
        
